# coding: utf8
import datetime
import logging as log
from pprint import pprint

from django.db import transaction

from app.base_controller import BaseController
from app.common import global_space
from app.models import User, Team, OrderTeam, OrderProducer, Producer, VideoOrder
from libs.util import check_param

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


def get_producer_list(self, team_status=[], producer_status=[]):
    session_id = self.get_argument("session_id", '')
    if check_param([session_id]):
        return self.render_json(code=1001, msg='参数不全')
    session = global_space.very_session(session_id)
    if not session:
        return self.render_json(code=999, msg='session 失效')
    user = User.objects.filter(id=session['id']).first()
    if not user or user.user_state not in [2, 3]:
        return self.render_json(code=1001, msg='用户状态不对')
    if user.user_state == User.TEAM:
        team = Team.objects.filter(owner=user).first()
        if not team:
            return self.render_json(code=1001, msg='用户状态不对')
        new_list = OrderTeam.objects.filter(state=0, team=team, order_status__in=team_status)

    elif user.user_state == User.PRODUCER:
        producer = Producer.objects.filter(user=user).first()
        if not producer:
            return self.render_json(code=1001, msg='用户状态不对')
        new_list = OrderProducer.objects.filter(state=0, order_status__in=producer_status, producer=producer)
    new_list = new_list.order_by('-create_time').all()
    paginator = self.pagination(new_list, number_per_page=int(self.get_argument("pageSize", 10)), page_num=int(self.get_argument("pageNum", 1)), photo_style='')
    return self.render_json(data=paginator)

#抢单的列表
class NewProducerOrders(BaseController):
    # 0普通用户1客户经理2团队老大3普通生产者
    def get(self):

        session_id = self.get_argument("session_id", '')
        if check_param([session_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user or user.user_state not in [2, 3]:
            return self.render_json(code=1001, msg='用户状态不对')
        if user.user_state == User.TEAM:
            team = Team.objects.filter(owner=user).first()
            if not team:
                return self.render_json(code=1001, msg='用户状态不对')
            new_list = OrderTeam.objects.filter(state=0, order_status__in=[OrderTeam.PP])

        elif user.user_state == User.PRODUCER:
            producer = Producer.objects.filter(user=user).first()
            if not producer:
                return self.render_json(code=1001, msg='用户状态不对')
            new_list = OrderProducer.objects.filter(state=0, order_status__in=[OrderProducer.PP])
        new_list = new_list.order_by('-create_time').all()
        paginator = self.pagination(new_list, number_per_page=int(self.get_argument("pageSize", 10)), page_num=int(self.get_argument("pageNum", 1)), photo_style='')
        return self.render_json(data=paginator)

#进行中订单
class RuningProducerOrders(BaseController):
    def get(self):
        return get_producer_list(self, [OrderTeam.BJ, OrderTeam.PS, OrderTeam.JJ], [OrderProducer.ZZZ])

#已完成订单
class FinishProducerOrders(BaseController):
    def get(self):
        return get_producer_list(self, [OrderTeam.DYS, OrderTeam.DPJ, OrderTeam.WC, OrderTeam.YTK], [OrderProducer.DYS, OrderProducer.DPJ, OrderProducer.WC, OrderProducer.YTK])

#订单统计
class StaticProducerOrders(BaseController):
    # 0普通用户1客户经理2团队老大3普通生产者
    def get(self):
        session_id = self.get_argument("session_id", '')
        if check_param([session_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user or user.user_state not in [2, 3]:
            return self.render_json(code=1001, msg='用户状态不对')

        data = {'total_num': 0, 'total_amont': 0, 'curent_month_num': 0, 'curent_month_amount': 0}
        curent_month = datetime.datetime.now().strftime('%Y-%m')
        if user.user_state == User.TEAM:
            team = Team.objects.filter(owner=user).first()
            if not team:
                return self.render_json(code=1001, msg='用户状态不对')
            for key in OrderTeam.objects.filter(state=0, team=team, order_status__in=[OrderTeam.DYS, OrderTeam.DPJ, OrderTeam.WC]).all():
                data['total_num'] += 1
                data['total_amont'] += key.amount*0.01
                if key.end_time and key.end_time.strftime('%Y-%m') == curent_month:
                    data['curent_month_num'] += 1
                    data['curent_month_amount'] += key.amount*0.01
        elif user.user_state == User.PRODUCER:
            producer = Producer.objects.filter(user=user).first()
            if not producer:
                return self.render_json(code=1001, msg='用户状态不对')
            data = {'total_num': 0, 'total_amont': 0, 'curent_month_num': 0, 'curent_month_amount': 0}
            for key in OrderProducer.objects.filter(state=0, order_status__in=[OrderProducer.DYS, OrderProducer.DPJ, OrderProducer.WC], producer=producer).all():
                data['total_num'] += 1
                data['total_amont'] += key.amount*0.01
                if key.end_time.strftime('%Y-%m') == curent_month:
                    data['curent_month_num'] += 1
                    data['curent_month_amount'] += key.amount*0.01
        return self.render_json(data=data)

#抢单
class GetOrder(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        id = self.get_argument("id", '')
        if check_param([session_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user or user.user_state not in [2, 3]:
            return self.render_json(code=1001, msg='用户状态不对')
        get_flag = False
        if user.user_state == User.TEAM:
            team = Team.objects.filter(owner=user).first()
            if not team:
                return self.render_json(code=1001, msg='用户状态不对')
            with transaction.atomic():
                team_order = OrderTeam.objects.select_for_update().get(pk=id)
                if team_order and team_order.order_status == OrderTeam.PP:
                    team_order.team = team
                    team_order.order_status = OrderTeam.BJ
                    get_flag = True
                    order = team_order.order
                    order.order_status = VideoOrder.STATE_WRITING
                    order.save()
                team_order.save()
        elif user.user_state == User.PRODUCER:
            producer = Producer.objects.filter(user=user).first()
            if not producer:
                return self.render_json(code=1001, msg='用户状态不对')
            with transaction.atomic():
                producer_order = OrderProducer.objects.select_for_update().get(pk=id)
                if producer_order and producer_order.order_status == OrderProducer.PP:
                    producer_order.producer = producer
                    producer_order.order_status = OrderProducer.ZZZ
                    get_flag = True
                producer_order.save()
            all_finish = True
            o = OrderProducer.objects.filter(id=id).first().order
            for key in OrderProducer.objects.filter(order=o).all():
                if key.order_status!=OrderProducer.ZZZ:
                    all_finish = False
                    break
            if all_finish:
                o.order_status = VideoOrder.STATE_WRITING
                o.save()
        return self.render_json(data={'get_flag': get_flag})

#订单详情
class OrderDetail(BaseController):

    def get_format_datetime(self, datetime):
        if not datetime:
            return ''
        return datetime.strftime('%Y-%m-%d')

    def get(self):
        session_id = self.get_argument("session_id", '')
        id = self.get_argument("id", '')
        if check_param([session_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        print(user.to_dict())
        if not user or user.user_state not in [2, 3]:
            return self.render_json(code=1001, msg='用户状态不对')
        data = {}
        if user.user_state == User.TEAM:
            team = Team.objects.filter(owner=user).first()
            if not team:
                return self.render_json(code=1001, msg='用户状态不对')
            order_team = OrderTeam.objects.filter(id=id).first()
            data['id'] = order_team.id
            data['team'] = 1
            data['start_time'] = self.get_format_datetime(order_team.start_time)
            data['end_time'] = self.get_format_datetime(order_team.end_time)
            if not order_team.plan_start_time:
                data['plan_start_time'] = data['start_time']
            else:    
                data['plan_start_time'] = order_team.plan_start_time.strftime('%Y-%m-%d')
            data['plan_end_time'] = self.get_format_datetime(order_team.plan_end_time)
            data['photo_start_time'] = self.get_format_datetime(order_team.photo_start_time)
            data['photo_end_time'] = self.get_format_datetime(order_team.photo_end_time)
            data['edit_start_time'] = self.get_format_datetime(order_team.edit_start_time)
            if not order_team.edit_end_time:
                data['edit_end_time'] = data['end_time']
            else:
                data['edit_end_time'] = self.get_format_datetime(order_team.edit_end_time)

            # if order_team.order_status==OrderTeam.BJ:
            #     data['start_time'] = order_team.plan_start_time.strftime('%Y-%m-%d')
            #     data['end_time'] = order_team.plan_end_time.strftime('%Y-%m-%d')
            # elif order_team.order_status==OrderTeam.PS:
            #     data['start_time'] = order_team.photo_start_time.strftime('%Y-%m-%d')
            #     data['end_time'] = order_team.photo_end_time.strftime('%Y-%m-%d')
            # elif order_team.order_status==OrderTeam.JJ:
            #     data['start_time'] = order_team.edit_start_time.strftime('%Y-%m-%d')
            #     data['end_time'] = order_team.edit_end_time.strftime('%Y-%m-%d')
            # else:
            #     data['start_time'] = order_team.plan_start_time.strftime('%Y-%m-%d')
            #     data['end_time'] = order_team.edit_end_time.strftime('%Y-%m-%d')
            data['amount'] = order_team.amount*0.01
            data['order_no'] = order_team.order.order_id
            data['customer_name'] = order_team.order.contact
            data['video_type'] = order_team.order.video_type.name
            data['shoot_day'] = order_team.order.shoot_day
            data['video_duration'] = order_team.order.video_duration
            data['city'] = order_team.order.city
            data['requirement'] = order_team.order.requirement
            data['status'] = order_team.order_status
            data['other_info'] = order_team.order.get_elements_info()
            data['title'] = order_team.order.title
            data['order_create_time'] = order_team.order.create_time.strftime('%Y-%m-%d')
            if order_team.order.video:
                data['video_name'] = order_team.order.video.title
                data['video_url'] = order_team.order.video.url
            pprint(data)


        elif user.user_state == User.PRODUCER:
            producer = Producer.objects.filter(user=user).first()
            if not producer:
                return self.render_json(code=1001, msg='用户状态不对')
            producer_order = OrderProducer.objects.filter(id=id).first()
            data['id'] = producer_order.id
            data['team'] = 0
            data['start_time'] = producer_order.start_time.strftime('%Y-%m-%d')
            data['end_time'] = producer_order.end_time.strftime('%Y-%m-%d')
            data['amount'] = producer_order.amount*0.01
            data['order_no'] = producer_order.order.order_id
            data['customer_name'] = producer_order.order.contact
            data['video_type'] = producer_order.order.video_type.name
            data['shoot_day'] = producer_order.excute_day
            data['video_duration'] = producer_order.order.video_duration
            data['city'] = producer_order.order.city
            data['status'] = producer_order.order_status
            data['requirement'] = producer_order.order.requirement
            data['other_info'] = producer_order.element.name + 'x1'
            data['title'] = producer_order.order.title
            data['order_create_time'] = producer_order.order.create_time.strftime('%Y-%m-%d')
            if producer_order.producer_finish_time:
                data['producer_finish_time'] = producer_order.producer_finish_time.strftime('%Y-%m-%d')
            if producer_order.order.video:
                data['video_name'] = producer_order.order.video.title
                data['video_url'] = producer_order.order.video.url
        pprint(data)
        return self.render_json(data=data)

#改变订单状态，团队可以从编剧中改到完成，分包只可以从进行中改到完成
class ChangeOrderStatus(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        id = self.get_argument("id", '')
        status = self.get_argument("status", '')

        if check_param([session_id, id, status]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user or user.user_state not in [2, 3]:
            return self.render_json(code=1001, msg='用户状态不对')

        if user.user_state == User.TEAM:
            if int(status) not in [OrderTeam.PS, OrderTeam.JJ, OrderTeam.DYS]:
                return self.render_json(code=1001, msg='修改的状态不对')

            team = Team.objects.filter(owner=user).first()
            if not team:
                return self.render_json(code=1001, msg='用户状态不对')
            order_team = OrderTeam.objects.filter(id=id).first()
            if not order_team:
                return self.render_json(code=1001, msg='订单不存在')
            if order_team.order_status not in [2, 3, 4]:
                return self.render_json(code=1001, msg='订单状态不对')
            # if int(status) == OrderTeam.PS and order_team.order_status != OrderTeam.BJ:
            #     return self.render_json(code=1001, msg='订单状态不对')
            # if int(status) == OrderTeam.JJ and order_team.order_status != OrderTeam.PS:
            #     return self.render_json(code=1001, msg='订单状态不对')
            # if int(status) == OrderTeam.DYS and order_team.order_status != OrderTeam.JJ:
            #     return self.render_json(code=1001, msg='订单状态不对')
            order_team.order_status = status
            order_team.save()

        elif user.user_state == User.PRODUCER:
            if int(status) != OrderProducer.DYS:
                return self.render_json(code=1001, msg='修改的状态不对')
            producer = Producer.objects.filter(user=user).first()
            if not producer:
                return self.render_json(code=1001, msg='用户状态不对')
            producer_order = OrderProducer.objects.filter(id=id).first()
            if not producer_order:
                return self.render_json(code=1001, msg='订单不存在')
            if producer_order.order_status != OrderProducer.ZZZ:
                return self.render_json(code=1001, msg='修改的状态不对')
            producer_order.order_status = OrderProducer.DYS
            producer_order.producer_finish_time = datetime.datetime.now()
            producer_order.save()
        return self.render_json()


class UpdateOrderTeamTime(BaseController):

    def invalidate_datetime(self, start_time, end_time):
        if not start_time or not end_time:
            return False
        if start_time.replace(tzinfo=None) > end_time.replace(tzinfo=None):
            return True
        return False

    def post(self):
        """更新整包订单时间
        """
        session_id = self.get_json_argument("session_id", '')
        order_id = self.get_json_argument('order_no', '')
        id = self.get_json_argument('id', 0)
        key = self.get_json_argument('key', '')
        value = self.get_json_argument('value', '')
        if check_param([session_id, order_id, id, key, value]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session or 'id' not in session:
            return self.render_json(code=999, msg='session 失效')

        video_order = VideoOrder.objects.filter(order_id=order_id).first()
        if not video_order:
            return self.render_json(code=1001, msg='订单不存在') 

        order_team = OrderTeam.objects.filter(id=id).first()
        if not order_team:
            return self.render_json(code=1001, msg='整包数据不存在')
        tmp_time = datetime.datetime.strptime(value, '%Y-%m-%d')
        if self.invalidate_datetime(order_team.start_time, tmp_time):
            return self.render_json(code=1001, msg='设置的时间不能小于整个项目的开始时间')
        if self.invalidate_datetime(tmp_time, order_team.end_time):
            return self.render_json(code=1001, msg='设置的时间不能大于整个项目的结束时间')
        OrderTeam.objects.filter(id=id).update(**{key: value})
        return self.render_json(msg='更新成功')